<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222"><meta name="generator" content="Hexo 7.3.0">

  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next-haha.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next-haha.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next-haha.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/7.0.0/css/all.min.css" integrity="sha256-VHqXKFhhMxcpubYf9xiWdCiojEbY9NexQ4jh8AxbvcM=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.1.1/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">

<script class="next-config" data-name="main" type="application/json">{"hostname":"ming.theyan.gs","root":"/","images":"/images","scheme":"Pisces","darkmode":false,"version":"8.25.0","exturl":false,"sidebar":{"position":"left","width_expanded":320,"width_dual_column":240,"display":"post","padding":18,"offset":12},"hljswrap":true,"codeblock":{"theme":{"light":"default","dark":"stackoverflow-dark"},"prism":{"light":"prism","dark":"prism-dark"},"copy_button":{"enable":false,"style":null},"fold":{"enable":false,"height":500},"language":false},"bookmark":{"enable":true,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"stickytabs":false,"motion":{"enable":true,"async":false,"duration":200,"transition":{"menu_item":"fadeInDown","post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"},"path":"/search.xml","localsearch":{"enable":true,"top_n_per_article":1,"unescape":false,"preload":false,"trigger":"auto"}}</script><script src="/js/config.js" defer></script>

    <meta name="description" content="问题初现最早发现问题时是在做一个测试，把某个域名解析到内网的几台机器上（10.0.0.9 和 10.0.0.119），结果用客户端（10.0.0.200 和 10.0.0.201，都由于特殊原因没有关掉 IPv6）去连接测试时发现，连接都跑到 10.0.0.119 上了，10.0.0.9 上几乎没有连接！">
<meta property="og:type" content="article">
<meta property="og:title" content="Linux域名解析中的IP地址选择“亲和性”问题">
<meta property="og:url" content="https://ming.theyan.gs/2017/07/Linux%E5%9F%9F%E5%90%8D%E8%A7%A3%E6%9E%90%E4%B8%AD%E7%9A%84IP%E5%9C%B0%E5%9D%80%E9%80%89%E6%8B%A9%E2%80%9C%E4%BA%B2%E5%92%8C%E6%80%A7%E2%80%9D%E9%97%AE%E9%A2%98/index.html">
<meta property="og:site_name" content="运维烂笔头">
<meta property="og:description" content="问题初现最早发现问题时是在做一个测试，把某个域名解析到内网的几台机器上（10.0.0.9 和 10.0.0.119），结果用客户端（10.0.0.200 和 10.0.0.201，都由于特殊原因没有关掉 IPv6）去连接测试时发现，连接都跑到 10.0.0.119 上了，10.0.0.9 上几乎没有连接！">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2017-07-15T09:48:02.000Z">
<meta property="article:modified_time" content="2017-07-15T09:48:02.000Z">
<meta property="article:author" content="老杨">
<meta property="article:tag" content="IPv6">
<meta property="article:tag" content="getaddrinfo">
<meta property="article:tag" content="gethostbyname">
<meta property="article:tag" content="glibc">
<meta property="article:tag" content="IPv4">
<meta property="article:tag" content="rfc3484">
<meta property="article:tag" content="gai.conf">
<meta name="twitter:card" content="summary">


<link rel="canonical" href="https://ming.theyan.gs/2017/07/Linux%E5%9F%9F%E5%90%8D%E8%A7%A3%E6%9E%90%E4%B8%AD%E7%9A%84IP%E5%9C%B0%E5%9D%80%E9%80%89%E6%8B%A9%E2%80%9C%E4%BA%B2%E5%92%8C%E6%80%A7%E2%80%9D%E9%97%AE%E9%A2%98/">


<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-CN","comments":true,"permalink":"https://ming.theyan.gs/2017/07/Linux%E5%9F%9F%E5%90%8D%E8%A7%A3%E6%9E%90%E4%B8%AD%E7%9A%84IP%E5%9C%B0%E5%9D%80%E9%80%89%E6%8B%A9%E2%80%9C%E4%BA%B2%E5%92%8C%E6%80%A7%E2%80%9D%E9%97%AE%E9%A2%98/index.html","path":"2017/07/Linux域名解析中的IP地址选择“亲和性”问题/index.html","title":"Linux域名解析中的IP地址选择“亲和性”问题"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>Linux域名解析中的IP地址选择“亲和性”问题 | 运维烂笔头</title>
  
    <script async src="https://www.googletagmanager.com/gtag/js?id=UA-106574959-2"></script>
  <script class="next-config" data-name="google_analytics" type="application/json">{"tracking_id":"UA-106574959-2","only_pageview":false,"measure_protocol_api_secret":null}</script>
  <script src="/js/third-party/analytics/google-analytics.js" defer></script>

  <script src="/js/third-party/analytics/baidu-analytics.js" defer></script>
  <script async src="https://hm.baidu.com/hm.js?fdef9ded31bdb8b2dab08eddebdd5fed"></script>







  
  <script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous" defer></script>
<script src="/js/utils.js" defer></script><script src="/js/motion.js" defer></script><script src="/js/sidebar.js" defer></script><script src="/js/next-boot.js" defer></script><script src="/js/bookmark.js" defer></script>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/hexo-generator-searchdb/1.5.0/search.js" integrity="sha256-xFC6PJ82SL9b3WkGjFavNiA9gm5z6UBxWPiu4CYjptg=" crossorigin="anonymous" defer></script>
<script src="/js/third-party/search/local-search.js" defer></script>







  




<!-- google adsense -->
<script data-ad-client="ca-pub-1045025618858716" async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>

  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
<link rel="alternate" href="/atom.xml" title="运维烂笔头" type="application/atom+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <div class="column">
      <header class="header" itemscope itemtype="http://schema.org/WPHeader"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <p class="site-title">运维烂笔头</p>
      <i class="logo-line"></i>
    </a>
      <p class="site-subtitle" itemprop="description">一个 SA 老兵的工作日志</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger" aria-label="搜索" role="button">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu"><li class="menu-item menu-item-projects"><a href="/projects" rel="section"><i class="fa fa-code fa-fw"></i>projects</a></li><li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a></li><li class="menu-item menu-item-about"><a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a></li><li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a></li><li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a></li><li class="menu-item menu-item-sitemap"><a href="/sitemap.xml" rel="section"><i class="fa fa-sitemap fa-fw"></i>站点地图</a></li><li class="menu-item menu-item-commonweal"><a href="/404/" rel="section"><i class="fa fa-heartbeat fa-fw"></i>公益 404</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
      <div class="search-header">
        <span class="search-icon">
          <i class="fa fa-search"></i>
        </span>
        <div class="search-input-container">
          <input autocomplete="off" autocapitalize="off" maxlength="80"
                placeholder="搜索..." spellcheck="false"
                type="search" class="search-input">
        </div>
        <span class="popup-btn-close" role="button">
          <i class="fa fa-times-circle"></i>
        </span>
      </div>
      <div class="search-result-container">
        <div class="search-result-icon">
          <i class="fa fa-spinner fa-pulse fa-5x"></i>
        </div>
      </div>
    </div>
  </div>

</header>
        
  
  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#%E9%97%AE%E9%A2%98%E5%88%9D%E7%8E%B0"><span class="nav-number">1.</span> <span class="nav-text">问题初现</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E9%97%AE%E9%A2%98%E5%8E%9F%E5%9B%A0"><span class="nav-number">2.</span> <span class="nav-text">问题原因</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E8%A7%A3%E5%86%B3%E6%96%B9%E6%B3%95"><span class="nav-number">3.</span> <span class="nav-text">解决方法</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E6%B5%8B%E8%AF%95%E6%B1%82%E8%AF%81"><span class="nav-number">4.</span> <span class="nav-text">测试求证</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E9%99%84%E5%BD%95"><span class="nav-number">5.</span> <span class="nav-text">附录</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%BE%8B%E7%A8%8Bgetaddrinfo-c"><span class="nav-number">5.1.</span> <span class="nav-text">例程getaddrinfo.c</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%B5%8B%E8%AF%95%E7%A8%8B%E5%BA%8F%E8%BF%90%E8%A1%8C"><span class="nav-number">5.2.</span> <span class="nav-text">测试程序运行</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%AE%89%E8%A3%85%E8%BD%AF%E4%BB%B6"><span class="nav-number">5.2.1.</span> <span class="nav-text">安装软件</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E7%BC%96%E8%AF%91%E5%8F%82%E6%95%B0"><span class="nav-number">5.2.2.</span> <span class="nav-text">编译参数</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#gdb%E8%B7%9F%E8%B8%AA"><span class="nav-number">5.2.3.</span> <span class="nav-text">gdb跟踪</span></a></li></ol></li></ol></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">老杨</p>
  <div class="site-description" itemprop="description">好记性比不过烂笔头</div>
</div>
<div class="site-state-wrap animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">114</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">8</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
          <a href="/tags/">
        <span class="site-state-item-count">509</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author animated">
      <span class="links-of-author-item">
        <a href="https://github.com/haw-haw" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;haw-haw" rel="noopener me" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="mailto:blog@theyan.gs" title="E-Mail → mailto:blog@theyan.gs" rel="noopener me" target="_blank"><i class="fa fa-envelope fa-fw"></i>E-Mail</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://weibo.com/u/1494877243" title="Weibo → https:&#x2F;&#x2F;weibo.com&#x2F;u&#x2F;1494877243" rel="noopener me" target="_blank"><i class="fab fa-weibo fa-fw"></i>Weibo</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://twitter.com/6fool" title="Twitter → https:&#x2F;&#x2F;twitter.com&#x2F;6fool" rel="noopener me" target="_blank"><i class="fab fa-twitter fa-fw"></i>Twitter</a>
      </span>
  </div>

        </div>
      </div>
    </div>

    
    <div class="sidebar-inner sidebar-blogroll">
      <div class="links-of-blogroll animated">
        <div class="links-of-blogroll-title"><i class="fa fa-globe fa-fw"></i>
          链接
        </div>
        <ul class="links-of-blogroll-list">
            <li class="links-of-blogroll-item">
              <a href="https://bad-pencil.github.io/" title="https:&#x2F;&#x2F;bad-pencil.github.io" rel="noopener" target="_blank">github 镜像站</a>
            </li>
            <li class="links-of-blogroll-item">
              <a href="https://hawhaw.gitee.io/" title="https:&#x2F;&#x2F;hawhaw.gitee.io" rel="noopener" target="_blank">gitee 镜像站</a>
            </li>
        </ul>
      </div>
    </div>
  </aside>


    </div>

    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://ming.theyan.gs/2017/07/Linux%E5%9F%9F%E5%90%8D%E8%A7%A3%E6%9E%90%E4%B8%AD%E7%9A%84IP%E5%9C%B0%E5%9D%80%E9%80%89%E6%8B%A9%E2%80%9C%E4%BA%B2%E5%92%8C%E6%80%A7%E2%80%9D%E9%97%AE%E9%A2%98/index.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="老杨">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="运维烂笔头">
      <meta itemprop="description" content="好记性比不过烂笔头">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="Linux域名解析中的IP地址选择“亲和性”问题 | 运维烂笔头">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          Linux域名解析中的IP地址选择“亲和性”问题
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2017-07-15 17:48:02" itemprop="dateCreated datePublished" datetime="2017-07-15T17:48:02+08:00">2017-07-15</time>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody"><h1 id="问题初现"><a href="#问题初现" class="headerlink" title="问题初现"></a>问题初现</h1><p>最早发现问题时是在做一个测试，把某个域名解析到内网的几台机器上（10.0.0.9 和 10.0.0.119），结果用客户端（10.0.0.200 和 10.0.0.201，都由于特殊原因没有关掉 IPv6）去连接测试时发现，连接都跑到 10.0.0.119 上了，10.0.0.9 上几乎没有连接！</p>
<a id="more"></a>
<h1 id="问题原因"><a href="#问题原因" class="headerlink" title="问题原因"></a>问题原因</h1><p>网上 Google 了一下，据说是新的域名解析系统调用 getaddrinfo() 加入了对 rfc3484 的支持导致的，这种支持会将 DNS 服务器返回某个域名的多个 IP（顺序随机），按照一定的逻辑排序后再返回，这样的话由于客户端一般都会取第一个 IP，所以我们看到的结果就是某个客户端老连一个 IP。</p>
<p>至于 rfc3484 中涉及到的排序逻辑，我的理解大概是优先返回跟客户端“最近”的 IP 地址（具体算法肯定远比这个复杂，但大概就是这个意思，所以我把 rfc3484 引入的这个问题称之为“亲和性”问题）。</p>
<p>我们的客户端的 IP 是 10.0.0.200 和 10.0.0.201，显然离 10.0.0.119 比离 10.0.0.9 更“近”，所以，连接都跑 10.0.0.119 上去了，10.0.0.9 上几乎没有连接。</p>
<h1 id="解决方法"><a href="#解决方法" class="headerlink" title="解决方法"></a>解决方法</h1><ul>
<li>强制使用老系统调用：gethostbyname</li>
<li>系统里干掉 IPv6</li>
</ul>
<p>当然是第二种方法合适，因为这样我们不用动代码，而只需要配置下环境即可。</p>
<h1 id="测试求证"><a href="#测试求证" class="headerlink" title="测试求证"></a>测试求证</h1><p>本着打破沙锅问到底的精神，找了个简单程序调用 getaddrinfo，并跟进 glibc 的源代码里看到了 getaddrinfo 函数执行情况的细节。于是找了两台服务器（用作客户端）：</p>
<ul>
<li>10.0.0.3（IPv6 enabled）</li>
<li>10.0.0.233（IPv6 disabled）</li>
</ul>
<p>在这两台机器上分别跑 gai.c 编出来的二进制文件，发现 IPv6 启用的那台（10.0.0.3）域名解析始终首先返回 10.0.0.9，而 IPv6 disabled 的那台（10.0.0.233）却一会儿首先返回 10.0.0.119，一会儿又首先返回 10.0.0.9。</p>
<h1 id="附录"><a href="#附录" class="headerlink" title="附录"></a>附录</h1><h2 id="例程getaddrinfo-c"><a href="#例程getaddrinfo-c" class="headerlink" title="例程getaddrinfo.c"></a>例程getaddrinfo.c</h2><p>这个例程是网上翻出来的，连文件名、版权注释都没改。：）</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment"> * getaddrinfo.c - Simple example of using getaddrinfo(3) function.</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * Michal Ludvig &lt;michal@logix.cz&gt; (c) 2002, 2003</span></span><br><span class="line"><span class="comment"> * http://www.logix.cz/michal/devel/</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * License: public domain.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;stdio.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;string.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;stdlib.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;netdb.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;sys/types.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;sys/socket.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;arpa/inet.h&gt;</span></span></span><br><span class="line"></span><br><span class="line">	<span class="keyword">int</span></span><br><span class="line">lookup_host (<span class="keyword">const</span> <span class="keyword">char</span> *host)</span><br><span class="line">&#123;</span><br><span class="line">	<span class="class"><span class="keyword">struct</span> <span class="title">addrinfo</span> <span class="title">hints</span>, *<span class="title">res</span>;</span></span><br><span class="line">	<span class="keyword">int</span> errcode;</span><br><span class="line">	<span class="keyword">char</span> addrstr[<span class="number">100</span>];</span><br><span class="line">	<span class="keyword">void</span> *ptr;</span><br><span class="line"></span><br><span class="line">	<span class="built_in">memset</span> (&amp;hints, <span class="number">0</span>, <span class="keyword">sizeof</span> (hints));</span><br><span class="line">	hints.ai_family = PF_UNSPEC;</span><br><span class="line">	hints.ai_socktype = SOCK_STREAM;</span><br><span class="line">	hints.ai_flags |= AI_CANONNAME;</span><br><span class="line"></span><br><span class="line">	errcode = getaddrinfo (host, <span class="literal">NULL</span>, &amp;hints, &amp;res);</span><br><span class="line">	<span class="keyword">if</span> (errcode != <span class="number">0</span>)</span><br><span class="line">	&#123;</span><br><span class="line">		perror (<span class="string">"getaddrinfo"</span>);</span><br><span class="line">		<span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="built_in">printf</span> (<span class="string">"Host: %s\n"</span>, host);</span><br><span class="line">	<span class="keyword">while</span> (res)</span><br><span class="line">	&#123;</span><br><span class="line">		inet_ntop (res-&gt;ai_family, res-&gt;ai_addr-&gt;sa_data, addrstr, <span class="number">100</span>);</span><br><span class="line"></span><br><span class="line">		<span class="keyword">switch</span> (res-&gt;ai_family)</span><br><span class="line">		&#123;</span><br><span class="line">			<span class="keyword">case</span> AF_INET:</span><br><span class="line">				ptr = &amp;((struct sockaddr_in *) res-&gt;ai_addr)-&gt;sin_addr;</span><br><span class="line">				<span class="keyword">break</span>;</span><br><span class="line">			<span class="keyword">case</span> AF_INET6:</span><br><span class="line">				ptr = &amp;((struct sockaddr_in6 *) res-&gt;ai_addr)-&gt;sin6_addr;</span><br><span class="line">				<span class="keyword">break</span>;</span><br><span class="line">		&#125;</span><br><span class="line">		inet_ntop (res-&gt;ai_family, ptr, addrstr, <span class="number">100</span>);</span><br><span class="line">		<span class="built_in">printf</span> (<span class="string">"IPv%d address: %s (%s)\n"</span>, res-&gt;ai_family == PF_INET6 ? <span class="number">6</span> : <span class="number">4</span>,</span><br><span class="line">				addrstr, res-&gt;ai_canonname);</span><br><span class="line">		res = res-&gt;ai_next;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">	<span class="keyword">int</span></span><br><span class="line">main (<span class="keyword">int</span> argc, <span class="keyword">char</span> *argv[])</span><br><span class="line">&#123;</span><br><span class="line">	<span class="keyword">if</span> (argc &lt; <span class="number">2</span>)</span><br><span class="line">		<span class="built_in">exit</span> (<span class="number">1</span>);</span><br><span class="line">	<span class="keyword">return</span> lookup_host (argv[<span class="number">1</span>]);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="测试程序运行"><a href="#测试程序运行" class="headerlink" title="测试程序运行"></a>测试程序运行</h2><h3 id="安装软件"><a href="#安装软件" class="headerlink" title="安装软件"></a>安装软件</h3><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">debuginfo-install glibc-2.12-1.166.el6_7.3.x86_64;</span><br></pre></td></tr></table></figure>
<p>这里因为我的 glibc 版本是 2.12-1.166.el6_7.3</p>
<h3 id="编译参数"><a href="#编译参数" class="headerlink" title="编译参数"></a>编译参数</h3><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">gcc -g -o g getaddrinfo.c;</span><br><span class="line"><span class="comment"># 运行，gdb 调试</span></span><br><span class="line">gdb ./g</span><br></pre></td></tr></table></figure>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">break main</span><br><span class="line">run www.a.shifen.com</span><br><span class="line"># 再一步步跟吧</span><br></pre></td></tr></table></figure>
<h3 id="gdb跟踪"><a href="#gdb跟踪" class="headerlink" title="gdb跟踪"></a>gdb跟踪</h3><p>发现在 glibc 源代码里，/usr/src/debug/glibc-2.12-2-gc4ccff1/sysdeps/posix/getaddrinfo.c 文件中第 2436 行和 2437 行：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span> (in6ai != <span class="literal">NULL</span>)</span><br><span class="line">   qsort (in6ai, in6ailen, <span class="keyword">sizeof</span> (*in6ai), in6aicmp);</span><br></pre></td></tr></table></figure>
<p>这里的第 2437 行的函数 qsort 就是用来做排序的，前面的判断条件 in6ai != NULL 在有 IPv6 的环境里成立；反之在仅有 IPv4 的环境里不成立。这也就是干掉 IPv6 会直接规避掉这个大“坑”的直接原因。</p>

    </div>

    
    
    

    <footer class="post-footer">
          <div class="reward-container">
  <div>请我一杯咖啡吧！</div>
  <button>
    赞赏
  </button>
  <div class="post-reward">
      <div>
        <img src="/images/wechat-reward.png" alt="老杨 微信">
        <span>微信</span>
      </div>
      <div>
        <img src="/images/alipay-reward.png" alt="老杨 支付宝">
        <span>支付宝</span>
      </div>

  </div>
</div>

          <div class="followme">
  <span>欢迎关注我的其它发布渠道</span>

  <div class="social-list">

      <div class="social-item">
          <a target="_blank" class="social-link" href="https://twitter.com/6fool">
            <span class="icon">
              <i class="fab fa-twitter"></i>
            </span>

            <span class="label">Twitter</span>
          </a>
      </div>

      <div class="social-item">
          <a target="_blank" class="social-link" href="/atom.xml">
            <span class="icon">
              <i class="fa fa-rss"></i>
            </span>

            <span class="label">RSS</span>
          </a>
      </div>
  </div>
</div>

          <div class="post-tags">
              <a href="/tags/IPv6/" rel="tag"># IPv6</a>
              <a href="/tags/getaddrinfo/" rel="tag"># getaddrinfo</a>
              <a href="/tags/gethostbyname/" rel="tag"># gethostbyname</a>
              <a href="/tags/glibc/" rel="tag"># glibc</a>
              <a href="/tags/IPv4/" rel="tag"># IPv4</a>
              <a href="/tags/rfc3484/" rel="tag"># rfc3484</a>
              <a href="/tags/gai-conf/" rel="tag"># gai.conf</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/2017/06/%E6%80%8E%E6%A0%B7%E5%9C%A8macOS%E4%B8%8A%E6%8A%93iPhone%E7%9A%84%E6%95%B0%E6%8D%AE%E5%8C%85/index.html" rel="prev" title="怎样在macOS上抓iPhone的数据包">
                  <i class="fa fa-angle-left"></i> 怎样在macOS上抓iPhone的数据包
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/2017/08/How-to-migrate-your-own-NS-servers/index.html" rel="next" title="How to migrate your own NS servers">
                  How to migrate your own NS servers <i class="fa fa-angle-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">

  <div class="copyright">
    &copy; 
    <span itemprop="copyrightYear">2025</span>
    <span class="with-love">
      <i class="fa fa-heart"></i>
    </span>
    <span class="author" itemprop="copyrightHolder">老杨</span>
  </div>
  <div class="powered-by">由 <a href="https://hexo.io/" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/pisces/" rel="noopener" target="_blank">NexT.Pisces</a> 强力驱动
  </div>

    </div>
  </footer>

  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>
  <div class="sidebar-dimmer"></div>
  <div class="back-to-top" role="button" aria-label="返回顶部">
    <i class="fa fa-arrow-up fa-lg"></i>
    <span>0%</span>
  </div>
  <a role="button" class="book-mark-link book-mark-link-fixed"></a>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>

</body>
</html>
